package br.com.caiocarrara.goodbuy.controller;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.ValidationMessage;
import br.com.caiocarrara.goodbuy.dao.UserDao;
import br.com.caiocarrara.goodbuy.interceptor.Restrict;
import br.com.caiocarrara.goodbuy.model.User;
import br.com.caiocarrara.goodbuy.model.UserLogged;

@Resource
public class UsersController {
	private final UserDao userDao;
	private final Result result;
	private final Validator validator;
	private final UserLogged userLogged;
	
	public UsersController(UserDao userDao, Result result, Validator validator, UserLogged userLogged ) {
		this.userDao = userDao;	
		this.result = result;
		this.validator = validator;
		this.userLogged = userLogged;
	}
	
	@Get("/users/new")
	public void newUser() {	}
	
	@Post("/users")
	public void add(User user) {
		if (this.userDao.exists(user))
			this.validator.add(new ValidationMessage("User already exists", "user.login"));
		
		this.validator.onErrorUsePageOf(this).newUser();
		
		this.userDao.add(user);
		
		this.result.redirectTo(ProductsController.class).list();
	}
	
	@Get("/login")
	public void loginForm() { }
	
	@Post("/login")
	public void login(User user) {
		User userLoaded = userDao.load(user);
		
		if (userLoaded == null)
			this.validator.add(new ValidationMessage("Invalid user or password", "user.login"));
		
		validator.onErrorUsePageOf(this).loginForm();
		
		userLogged.login(userLoaded);
		
		result.redirectTo(ProductsController.class).list();
	}
	
	@Get("/logout")
	@Restrict
	public void logout() {
		this.userLogged.logout();
		this.result.redirectTo(ProductsController.class).list();
	}
}
